// 运行时配置
import type { RequestConfig } from '@umijs/max';
import { message } from 'antd';
import dayjs from 'dayjs';
import { LoginDataVO } from '@/services/UserService';

dayjs.locale('zh-cn');

// 需要登录的接口路径
const loginUrls = [
  'user/logout',
  'user/info',
  'messages_board/like',
  'messages_board'
];

interface ResponseData {
  code: number;
  data: any;
  message?: string;
}

export const request: RequestConfig = {
  // 全局配置
  baseURL: '/api',
  timeout: 60000,
  // other axios options you want
  errorConfig: {
    errorHandler: (error: any) => {
      message.error(error.message);
    },
    errorThrower: () => {},
  },
  requestInterceptors: [
    (config: any) => {
      const token = localStorage.getItem('token');
      const user = localStorage.getItem('user');
      console.log(user);
      console.log(token);
      if (token && token !== 'undefined') {
        const headers = {
          ...config.headers,
          Authorization: `Bearer ${token}`,
        };
        return { ...config, headers };
      }
      return config;
    }
  ],

  // 响应拦截器
  responseInterceptors: [
    (response: any) => {
      const data = response.data as ResponseData;
      console.log('Response data:', data);
      console.log('Request URL:', response.config?.url);
      
      // 处理需要登录的情况
      if (data.code === 777) {
        // 检查是否是需要登录的接口
        const requestUrl = response.config?.url || '';
        console.log('Checking URL:', requestUrl);
        
        const isLoginRequired = loginUrls.some(url => {
          const match = requestUrl.includes(url);
          console.log(`Checking ${url} against ${requestUrl}: ${match}`);
          return match;
        });

        console.log('Login required:', isLoginRequired);

        if (isLoginRequired) {
          console.log('Triggering login modal');
          // 触发全局状态更新，显示登录框
          window.dispatchEvent(new CustomEvent('showLoginModal'));
          // 直接返回响应数据，不抛出错误
          return response.data;
        }
      }
      
      // 处理非200状态码的情况
      if (data.code !== 200) {
        // message.error(data.message || '操作失败');
        throw new Error(data.message || '操作失败');
      }
      
      // 返回原始响应数据
      return response.data;
    }
  ],
};
